﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace max_cfg_tool
{
    class Program
    {
        static string[] ParseLine(string line)
        {
            return line.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
        }
        static string[] ReadCsvFile(string filePath)
        {
            string[] lines = new string[1024];
            int index = 0;
            using (var reader = new StreamReader(filePath, Encoding.UTF8))
            {
                string line;
                while ((line = reader.ReadLine()) != null)
                {

                    lines[index] = line;
                    index++;
                }
            }

            return lines;
        }

        static int get_addr_value(string addr,string value,ref byte addr_byte,ref byte vaue_byte)
        {
            try
            {
                addr = addr.Replace("h","");
                addr = addr.Replace("H", "");
                addr = addr.Replace(" ", "");

                value = value.Replace("h", "");
                value = value.Replace("H", "");
                value = value.Replace(" ", "");

                addr_byte = Convert.ToByte(addr, 16);
                vaue_byte = Convert.ToByte(value, 16);


            }
            catch (Exception)
            {

                return -1;
            }
            return 0x0;
        }
        static void Main(string[] args)
        {
            string csv_path = "max86176 configuration file for typical application.csv";
            string[] lines = new string[1024];
            lines = ReadCsvFile(csv_path);
            int ret = 0;
            byte reg_addr=0;
            byte reg_value=0;

            string out_file_path = "max_cfg.bin";
            FileStream file_out_out = new FileStream(out_file_path, FileMode.Create, FileAccess.ReadWrite);
            BinaryWriter writer = new BinaryWriter(file_out_out);
            int valid_data_count = 0;
            for (int i = 0; i < lines.Count(); i++)
            {
                if(lines[i]==null)
                {
                    continue;
                }
                string[] number = new string[512];
                number = lines[i].Split(',');

                ret = get_addr_value(number[0], number[2], ref reg_addr, ref reg_value);
                if(ret==0)//数据有效
                {
                    writer.Write(reg_addr);
                    writer.Write(reg_value);
                    valid_data_count++;
                    Console.WriteLine("reg_addr=0x{0:x},reg_value=0x{1:x}", reg_addr, reg_value);
                }
               
            }
            Console.WriteLine("done,valid_data_count={0}",  valid_data_count);

            writer.Flush();
            return;
        }
    }
}
